<?php

App::uses('WeixinUtility', 'Utility');
App::uses('WeixinCompUtility', 'Utility');
App::uses('CrawlUtility', 'Utility');

define('WX_PREVIEW_SCENE_ID',1350000000);

class WxAppController extends AppController{
	
	var $components = array(
    	'Auth' => array(
					'authenticate' => array(
							'Form'=>array(
									'userModel' => 'User','recursive' => 1,
									'fields'=>array(
											'username'=>'email',
											'password'=>'password'
									)
							),
					),
					'authorize' => array(
						'all' => array(
							'actionPath' => 'controllers/'
						),
						'Crud',
					)
			),
    );
	
	var $current_wxinfo = null; // 当前编辑管理的微信号信息，
	var $user_wxes = array();
	var $varibales = array();
	var $show_wxinfo = array(); // 当前用户正在访问的微信号
	var $cities = array();
	protected $datainfo = array();
	
	var $show_wx_menu = true;
	
	public function beforeFilter(){
		
		//$this->Auth->allowedActions = array_merge($this->Auth->allowedActions,array('view','lists','mine','anony','index'));
	    $this->Auth->allowedActions = array_merge($this->Auth->allowedActions,array('anony'));
		
		parent::beforeFilter();
		
		if( $this->currentUser['id'] && !in_array($this->action,array('view','anony','index','lists')) )
		{
            $current_wxid = $_REQUEST['manage_wxid']?$_REQUEST['manage_wxid']:$_REQUEST['wx_id'];

            $this->loadModel('Wx');

            if($this->Session) {
                $this->user_wxes = $this->Session->read('User.wxes');
                if(empty($current_wxid)) {
                    $current_wxid = $this->Session->read('User.current_wxid');
                }
            }

			if( empty($this->user_wxes) ) {
			    $limit = 1;
			    /* 数值大的要放到前面 */
			    if( !empty($this->currentUser['role_id']) ){
			        if( in_array(12,$this->currentUser['role_id'])   ||  max($this->currentUser['role_id']) > 49 ) { // 12为企业级，允许50个微信号
			            $limit = 50;
			        }
			        elseif( in_array(13,$this->currentUser['role_id']) ) { // 13为初级企业会员，只允许10个微信号
			            $limit = 10;
			        }
			        elseif( in_array(9,$this->currentUser['role_id']) ) { // 9为高级，只允许10个微信号
			            $limit = 10;
			        }
			        elseif( in_array(10,$this->currentUser['role_id']) ) { //10为中级，只允许5个微信号
			            $limit = 5;
			        }
			        elseif( in_array(8,$this->currentUser['role_id']) ) { //8为初级，只允许2个微信号
			            $limit = 2;
			        }
			    }

			    // 中高级用户支持多人客服聊天。$limit >= 5 &&
			    if(  $_REQUEST['company_id'] && $_REQUEST['company_id'] == $this->currentUser['company_id'] ) {
			        $this->loadModel('CompanyMember');
			        $users = $this->CompanyMember->find('all',array(
			            'conditions' => array('company_id'=>$_REQUEST['company_id']),
			            'fields' => array('company_id','user_id'),
			        ));
    				$uids = array();
    				foreach($users as $u){
    					$uids[] = $u['CompanyMember']['user_id'];

    				}
			        $wx_conditions = array('Wx.creator' => $uids,'is_company'=>1 );
			    }
			    else{
			        $wx_conditions = array('Wx.creator' => $this->currentUser['id']);
			    }

				$this->user_wxes = $this->Wx->find('all',array(
						'conditions'=> $wx_conditions	,
						'joins' => array(array(
							'table' => 'oauthbinds',
							'alias' => 'Oauthbind',
							'type' => 'left',
							'conditions' => array(
								'Wx.creator=Oauthbind.user_id',
								'Wx.oauth_appid=Oauthbind.oauth_openid',
								'Oauthbind.source'=>'wechatComp',
							)
						)),
				        'order' => 'Oauthbind.updated desc',
				        'fields' => 'Wx.*,Oauthbind.*',
				        'limit' => $limit,
				));

				// 只刷新选择的微信授权，或者默认选择的微信授权
				foreach ($this->user_wxes as $k => $wx) {
				    if($wx['Oauthbind']['updated'] < time() - 7100) {
				        if($current_wxid && $wx['Wx']['id'] !== $current_wxid ){
				            continue;
				        }
				        elseif( empty($current_wxid) && $k > 0){
				            continue;
				        }
				        if(empty($wx['Oauthbind']['refresh_token'])) { //已经取消授权了
				            continue;
				        }

				        $refresh_result = WeixinCompUtility::refreshToken($wx['Oauthbind']['oauth_openid'],$wx['Oauthbind']['refresh_token']);
				        if(empty($refresh_result)) { // 网络原因未取得结果，跳过不处理。下次继续请求
				            $refresh_result = WeixinCompUtility::refreshToken($wx['Oauthbind']['oauth_openid'],$wx['Oauthbind']['refresh_token']);
				            if(empty($refresh_result)) {
// 				                unset($this->user_wxes[$k]); //过期刷新失败
				                continue;
				            }
				        }
				        if(empty($refresh_result['errcode']) && !empty($refresh_result['authorizer_access_token'])){
				            $this->loadModel('Oauthbind');
				            $this->Oauthbind->updateAll(array(
				                'oauth_token' => $this->Oauthbind->escape_string($refresh_result['authorizer_access_token']),
				                'expires' => $refresh_result['expires_in'],
				                'refresh_token' => $this->Oauthbind->escape_string($refresh_result['authorizer_refresh_token']),
				                'updated' => time(),
				            ),array('id'=>$wx['Oauthbind']['id']));
				        }
				        else{
				            unset($this->user_wxes[$k]); //过期刷新失败的从列表中删除。
				        }
				    }
				}
                if($this->Session) {
                    $this->Session->write('User.wxes', $this->user_wxes);
                }
			}
			
			if( $current_wxid ){
				foreach($this->user_wxes as $wx){
					if( $current_wxid == $wx['Wx']['id'])	{
						$this->current_wxinfo = $wx;
						break;
					}
				}
				if(empty($this->current_wxinfo) && $this->modelClass != 'WxMsg' ){
					$this->current_wxinfo = $this->Wx->find('first',array(
						'conditions'=> 	array( 'id'=> $current_wxid, 'Wx.creator' => $this->currentUser['id']),
					));
				}
                if($this->Session) {
                    $this->Session->write('User.current_wxid', $this->current_wxinfo['Wx']['id']);
                }
			}
						
			if( empty($this->current_wxinfo) && !empty($this->user_wxes) ) {
				$this->current_wxinfo = current($this->user_wxes);
                if($this->Session) {
                    $this->Session->write('User.current_wxid', $this->current_wxinfo['Wx']['id']);
                }
			}
			
			if( !empty($this->current_wxinfo['Wx']['oauth_appid']) ){
				WeixinUtility::$appId = $this->current_wxinfo['Wx']['oauth_appid'];
			}
			
			//'Wxes','WxMsgs' 两模块无需强制必须有公众号
// 			if( empty($this->current_wxinfo) && !in_array($this->name,array('Wxes','WxMsgs','CourseMsgs','UserSettings')) ){
// 				$this->Session->setFlash(__('bind_wechat_tips'));
// 				$this->redirect('/wxes/mine');
// 			}
			
		    $settings = $this->currentUser['UserSetting'];
            $wx_id = $this->current_wxinfo['Wx']['id'];
            if($wx_id) {
                $this->varibales = $settings[$wx_id];
                if( !empty($this->varibales['wxAppId']) ) {
                    WeixinUtility::$appId = $this->varibales['wxAppId'];
                    WeixinUtility::$secretKey = $this->varibales['wxAppSecret'];
                }
            }
            else{
                $this->varibales = $settings;
            }
		}
	}

	protected function getWxOpenId($appid){
		if($this->request->is('weixin')) {
    		$wx_open_id = $this->Session->read('wx_openid_'.$appid);
    		if( empty($wx_open_id) ) {
    			$state = base64_encode(Router::url(null,true));
    			$redirect = 'http://www.135plat.com/wxes/oauth_base/'.$appid;

    			/*
    			1、以snsapi_base为scope发起的网页授权，是用来获取进入页面的用户的openid的，并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页（往往是业务页面）
2、以snsapi_userinfo为scope发起的网页授权，是用来获取用户的基本信息的。但这种授权需要用户手动同意，并且由于用户同意过，所以无须关注，就可在授权后获取该用户的基本信息。
3、用户管理类接口中的“获取用户基本信息接口”，是在用户和公众号产生消息交互或关注后事件推送后，才能根据用户OpenID来获取用户基本信息。这个接口，包括其他微信接口，都是需要该用户（即openid）关注了公众号后，才能调用成功的。
*/

    			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state='.$state.'#wechat_redirect';
    			$this->redirect($url);
    		}
    		return $wx_open_id;
    	}
    	return false;
	}
	
	public function view($slug) {
	    parent::view($slug);
	    $this->layout = 'wechat';
	    
	    $wx_id = $this->item[$this->modelClass]['wx_id'];
	    
	    if(empty($this->current_wxinfo) || $this->current_wxinfo['Wx']['id'] != $wx_id ) {	    
    	    $this->loadModel('Wx');
	        $this->current_wxinfo = $this->Wx->find('first',array(
    	        'conditions'=> array('id'=>$wx_id),
    	        'recursive' => -1,    	        
    	    ));

    	    /*if( $this->modelClass != 'WxMsg' &&  !empty($this->current_wxinfo) && $this->current_wxinfo['Wx']['oauth_appid'] ) {
    	    	$open_id = $this->getWxOpenId($this->current_wxinfo['Wx']['oauth_appid']);
    	    }*/
	    }
	}
	
	public function beforeRender() {
		
		$this->set('current_wxinfo',$this->current_wxinfo);
		$this->set('user_wxes',$this->user_wxes);
		
		$user_wx_lists = array();
		if(is_array($this->user_wxes)) {
			foreach($this->user_wxes as $wx){			
				$user_wx_lists[$wx['Wx']['id']] = $wx['Wx']['name'];
			}
			$this->set('user_wx_lists',$user_wx_lists);
		}
		
		if($this->show_wxinfo){
			$this->set('wxinfo', $this->show_wxinfo);
			Configure::write('Site.title', $this->show_wxinfo['Wx']['name']);
		}
		if ($this->RequestHandler->accepts('json') || $this->RequestHandler->isAjax() || isset($_GET['inajax'])) {
			$this->layout = 'ajax';
		}
		elseif($this->layout == 'default' && in_array($this->action,array('view','lists','anony','index'))) {
			$this->layout = 'wx_default';
		}
		
		$this->set('show_wx_menu',$this->show_wx_menu);
		parent::beforeRender();
	}
	

	protected function getCities(){
		$this->loadModel('WxCity');
		$city_list = $this->WxCity->find('all',array(
				'fields' => array('WxCity.city_id','City.name'),
				'conditions' => array('wx_id'=> $this->current_wxinfo['Wx']['id']),
				'joins' => array(array(
						'table'=>'cities',
						'alias' => 'City',
						'type' => 'inner',
						'conditions'=> array('WxCity.city_id=City.id'),
				)),
		));
		
		$this->cities[''] = __('Please Select a City');
		
		foreach ($city_list as $value) {
			$this->cities[$value['WxCity']['city_id']] = $value['City']['name'];
		}
		$this->set('cities', $this->cities);
	}
	
	public function add(){	
		$this->pageTitle = __('Add New').__d('modelextend',$this->modelClass);

		$schema = $this->{$this->modelClass}->schema();
		$fields = array_keys($schema);

		if ( empty($this->data) ) {
			//设置上级分类的选项
			if( in_array('cate_id',$fields) ){
				$this->loadModel('UserCate');
				$cates = $this->UserCate->getCateList($this->modelClass,$this->currentUser['id'],'',true);
				$this->set('cates', $cates);
			}
			// if(in_array('city_id',$fields)){
			// 	$this->getCities();
			// }
		}
		elseif( in_array('wx_id',$fields) ){
			$this->data[$this->modelClass]['wx_id'] = $this->current_wxinfo['Wx']['id'];
		}
		parent::add();
	}
	

	public function delete($id){
	    
	    $schema = $this->{$this->modelClass}->schema();
	    if(isset($schema['creator'])) {
	        $datainfo = $this->{$this->modelClass}->find('first', array(
	        				'conditions' => array('id' => $id, 'creator' => $this->currentUser['id']),
	        				'recursive' => -1,
	        ));
	    }
	    elseif(isset($schema['user_id'])) {
	        $datainfo = $this->{$this->modelClass}->find('first', array(
	        				'conditions' => array('id' => $id, 'user_id' => $this->currentUser['id']),
	        				'recursive' => -1,
	        ));
	    }
	     
	    if(empty($datainfo)) {
	        
	        $wx_ids =  array();
	        if(is_array($this->user_wxes)) {
	            foreach($this->user_wxes as $wx){
	                $wx_ids[] = $wx['Wx']['id'];
	            }
	        }
	        else{
	            throw new ForbiddenException(__('You cannot delete this data'));
	        }
	        
	        $datainfo = $this->{$this->modelClass}->find('first', array(
	            'conditions' => array( 'id' => $id, 'wx_id' => $wx_ids ),
	            'recursive' => -1,
	        ));
	    }
	     
	    if (empty($datainfo)) {
	        throw new ForbiddenException(__('You cannot delete this data'));
	    }
	    $this->{$this->modelClass}->deleteAll(array('id' => $id),true,true);
	    echo json_encode(array('ret'=>0,'msg'=> __('Delete Successfully')));
	    exit;
	}
	
	public function mine(){
		$this->pageTitle = __('My').__d('modelextend',$this->modelClass);

		if(empty($this->currentUser['id'])) {
			$this->redirect('/users/login?referer='.Router::url());
		}

		
		$this->loadModel('UserCate');
		$cates = $this->UserCate->getCateList($this->modelClass,$this->currentUser['id'],'',true);
		$this->set('cates', $cates);
		
		$this->getCities();
		
		$page = $_GET['page'] ? $_GET['page'] : 1;
		$limit = intval(Configure::read($this->modelClass.'.pagesize'));
		if(!$limit){
		    $limit = 20;
		}
		if(in_array($this->modelClass,array('WxActivity'))){
            $conditions = array( 'creator' => $this->currentUser['id']);
        }
        else{
            $conditions = array( 'creator' => $this->currentUser['id'],'wx_id' => $this->current_wxinfo['Wx']['id']);
        }
		$schema = $this->{$this->modelClass}->schema();
		foreach($_REQUEST as $key => $val){
			if( isset($schema[$key]) ){
				$conditions[$key] = $val;
			}
		}
		
		if( isset($schema['deleted']) ) {
		    $conditions['deleted'] = $_REQUEST['deleted'] ? 1 : 0;
		}
        if( isset($schema['updated']) ) {
            $order = $_GET['order'] ? $_GET['order'] . ' desc' : $this->modelClass . '.updated desc';
        }
        else{
            $order = $_GET['order'] ? $_GET['order'] . ' desc' : $this->modelClass . '.id desc';
        }
	
		$datalist = $this->{$this->modelClass}->find('all', array(
				'conditions' => $conditions,
				'limit'=> $limit,
				'page' => $page,
				'order' => $order,
				'recursive' => 1,
		));
		$total = $this->{$this->modelClass}->find('count', array(
				'conditions' => $conditions,
		));
		
		$page_navi = getPageLinks($total, $limit, $this->request, $page);
		$this->set('page_navi', $page_navi);
		
		$this->set('datalist',$datalist);
	}
	
	function edit($id) {
	
		$this->pageTitle = __('Edit').' '.__d('modelextend',$this->modelClass);
	
		$modelClass = $this->modelClass;
		
		$this->item = $datainfo = $this->{$this->modelClass}->find('first', array(
		    'conditions' => array('id' => $id, 'creator' => $this->currentUser['id']),
		    'recursive' => 1,
		));
		
		if (empty($datainfo)) {
			throw new ForbiddenException(__('You cannot edit this data'));
		}
	
		if (!empty($this->data)) { //有提交时
			
			$this->autoRender = false;
			$this->data[$modelClass]['creator'] = $this->currentUser['id'];
			$this->data[$modelClass]['view_nums'] = $datainfo[$modelClass]['view_nums'];
			//$this->data[$modelClass]['wx_id']  = $this->current_wxinfo['Wx']['id'];
	
			$hasError = 0;
			if ($this->{$this->modelClass}->save($this->data)) {
			    if(!empty($this->data['Uploadfile'])){
			        $this->loadModel('Uploadfile');
			        foreach($this->data['Uploadfile'] as $file){
			            $this->Uploadfile->create();
			            $fileinfo = array();
			            $fileinfo['id'] = $this->Uploadfile->id = $file['id'];
			            $fileinfo['user_id'] = $this->currentUser['id']; //用于获取分表
			            $fileinfo['data_id'] = $id;
			            // 只修改  data_id
			            $this->Uploadfile->save($fileinfo, true, array('data_id','user_id','id'));
			            // $this->Uploadfile->updateAll(array(),array());
			        }
			    }
			} else {
				$hasError = 1;
			}
			
			$redirect = $this->data[$this->modelClass]['referer'] ? $this->data[$this->modelClass]['referer'] : ($_REQUEST['referer'] ? $_REQUEST['referer'] : '');
			if(empty($redirect)){
				$redirect = Router::url(array('action'=>'view',$id));
			}
			if ($this->RequestHandler->accepts('json') || $this->RequestHandler->isAjax() || isset($_GET['inajax'])) {
			    $successinfo = array(
			    	'ret'=>0,
			    	'msg' => __('Edit success'),
			    	'data' => $this->data,
			    	'tasks' => array(
			    		array('dotype' => 'closedialog'),
			    		array('dotype'=>'location','url' => $redirect )
			    	)
			    );
            	
// 			    $this->set('successinfo', $successinfo);
// 			    $this->set('_serialize', 'successinfo');
			    $this->autoRender = false;
			    echo json_encode($successinfo); 
			    // $this->ajaxOutput($successinfo);
			    return true;
			}
			elseif($_REQUEST['return']){
				return $hasError;
			}
			else{
    			
    			$this->redirect($redirect);
			}
			//$this->redirect(array('action'=>'mine'));
		}
		else{
			
			//设置上级分类的选项
			$this->loadModel('UserCate');
			$cates = $this->UserCate->getCateList($this->modelClass,$this->currentUser['id'],'',true);
			$this->set('cates', $cates);
			
			$schema = $this->{$this->modelClass}->schema();
			$fields = array_keys($schema);
			if(in_array('city_id',$fields)){
				$this->getCities();
				// 不能这样新增项，否则导致城市的id序号都从零开始重新编号了
				//array_unshift($this->cities,__('Please Select')); $this->set('cities', $this->cities);
			}
			
			if( isset($this->data[$modelClass.'I18n']) ) {
				if( $this->data[$modelClass]['locale'] != getLocal(Configure::read('Site.language'))) {
					$locale = $this->data[$modelClass]['locale'];
					$this->data[$modelClass] = $this->data[$modelClass.'I18n'][$locale];
				}
			}
			
			$this->data = $datainfo; //设置表单各项的值
			
			$this->set('id',$id);
			$this->__loadFormValues($modelClass,$id);
		}
		$this->__viewFileName = 'add';
	}
}
